from asn1util import *
from .sm2 import *

logger = logging.getLogger(__name__)


def parse_pem_file(pem_file):
    with open(pem_file, 'rb') as f:
        return parse_pem_data(f.read())


def parse_pem_data(pem_data: bytes):
    res = []
    for name, content in iter_pem(pem_data):
        if name == 'PRIVATE KEY':
            private_key_info = ASN1Sequence.from_bytes(content).value
            version = private_key_info[0].value
            private_key_algorithm = private_key_info[1].value
            algorithm_identifier = private_key_algorithm[0]
            parameters = private_key_algorithm[1]

            if str(algorithm_identifier) != OID_EC_PUBLIC_KEY or str(parameters) != OID_SM2_ELLIPTIC_CURVE:
                logger.warning('不支持的密钥类型：{} {}'.format(algorithm_identifier, parameters))
                continue

            if version != 0:
                logger.warning('不支持的EC密钥版本：{} {}'.format(algorithm_identifier, parameters))
                continue

            private_key = ASN1Sequence.from_bytes(private_key_info[2].value).value
            private_key_version = private_key[0].value
            if private_key_version != 1:
                logger.warning('不支持的SM2密钥版本：{} {}'.format(algorithm_identifier, parameters))
                continue

            private_key_data = private_key[1].value
            res.append(SM2PrivateKey.from_bytes(private_key_data))

        else:
            logger.warning('不支持的PEM对象：{}'.format(name))
            continue
    return res


